<?php

namespace adminmatrix\migration\command;

use adminmatrix\migration\Command;
use Phinx\Seed\AbstractSeed;
use Phinx\Util\Util;
use think\migration\Seeder;
use InvalidArgumentException;
abstract class Seed extends Command
{
    protected $seeds;
    protected $appName;

    protected function getPath()
    {

        if (empty($this->appName)) {
            return $this->app->getRootPath() . 'database' . DIRECTORY_SEPARATOR . 'seeds';
        }
        return  $this->app->getAppPath() . $this->appName . DIRECTORY_SEPARATOR . 'database' . DIRECTORY_SEPARATOR . 'seeds';

    }

    protected function getSeeds()
    {
        if (null === $this->seeds)
        {
            $originalPattern = $this->getPath() . DIRECTORY_SEPARATOR . '*.php';
            $originalFiles = glob($originalPattern, defined('GLOB_BRACE') ? GLOB_BRACE : 0);

            $newPattern = $this->app->getAppPath()
                . '*'
                . DIRECTORY_SEPARATOR . 'database'
                . DIRECTORY_SEPARATOR . 'seeds'
                . DIRECTORY_SEPARATOR . '*.php';

            $newFiles = glob($newPattern, defined('GLOB_BRACE') ? GLOB_BRACE : 0);

            $phpFiles = array_unique(array_merge(
                $originalFiles ?: [],
                $newFiles ?: []
            ));

            // filter the files to only get the ones that match our naming scheme
            $fileNames = [];
            /** @var Seeder[] $seeds */
            $seeds = [];

            foreach ($phpFiles as $filePath) {
                if (Util::isValidSeedFileName(basename($filePath))) {
                    // convert the filename to a class name
                    $class             = pathinfo($filePath, PATHINFO_FILENAME);
                    $fileNames[$class] = basename($filePath);

                    // load the seed file
                    /** @noinspection PhpIncludeInspection */
                    require_once $filePath;
                    if (!class_exists($class)) {
                        throw new InvalidArgumentException(sprintf('Could not find class "%s" in file "%s"', $class, $filePath));
                    }

                    // instantiate it
                    $seed = new $class($this->input, $this->output);

                    if (!($seed instanceof AbstractSeed)) {
                        throw new InvalidArgumentException(sprintf('The class "%s" in file "%s" must extend \Phinx\Seed\AbstractSeed', $class, $filePath));
                    }

                    $seeds[$class] = $seed;
                }


            }

            ksort($seeds);
            $this->seeds = $seeds;
        }
        return $this->seeds;
    }


}